package cn.hh.wechatkit.api.user;

import cn.hh.wechatkit.api.token.WxAPI_Access_GetOpenId_Api;
import cn.hh.wechatkit.exception.Wx_Exception_GetTokenFailed;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hh.wechatkit.helper.CacheHelper;
import cn.hh.wechatkit.param.WxParam;
import cn.hh.wechatkit.pojo.token.WxApp_OpenIdSession;
import cn.hh.wechatkit.pojo.token.WxToken_AuthoAccessToken;
import cn.hh.wechatkit.pojo.user.Wx_UnionInfo;
import cn.hhchat.kit.http.httpUtil;
import okhttp3.Response;
import org.slf4j.Logger;
import java.io.IOException;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;

import static cn.hh.wechatkit.helper.WxConst.PullUserInfo_Get_URL;

/**
 * Created this one by HMH on 20«17/3/24.
 * Wx_UnionInfo 拉取用户数据API
 */

public class WxAPI_UnionInfo_Api {

    final static Logger logger = LoggerFactory.getLogger(WxAPI_UnionInfo_Api.class);

    /**
     * 获取用户基本信息
     * @param ACCESS_TOKEN 基础令牌
     * @param OPENID openId
     * @return Wx_UnionInfo 微信用户认证数据
     * @throws IOException io异常
     */
    public static Wx_UnionInfo getUnion_Info_By_OpenId(String ACCESS_TOKEN, String OPENID) throws IOException, Wx_Exception_InvalidJsonParse, Wx_Exception_InvalidResponse {

        Wx_UnionInfo wxUnionInfo;
        //生成url
        String url = PullUserInfo_Get_URL
                .replace("ACCESS_TOKEN", ACCESS_TOKEN)
                .replace("OPENID", OPENID);
        //发起请求
        Response response = httpUtil.get(url);
        if (response != null) {
            try {
                String body = response.body().string();
                wxUnionInfo = JSONObject.parseObject(body, Wx_UnionInfo.class);
                return wxUnionInfo;
            } catch (IOException e) {
                throw new Wx_Exception_InvalidJsonParse("处理返回的JsApiToken发生错误\n",e);
            }
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }

    public static Wx_UnionInfo getUnion_Info_By_AuthoCode(String ACCESS_TOKEN,String code) throws Wx_Exception_GetTokenFailed, Wx_Exception_InvalidResponse, Wx_Exception_InvalidJsonParse, IOException {
        WxToken_AuthoAccessToken authoAccessToken = CacheHelper.getAuthoAccessToken(code);
        return getUnion_Info_By_OpenId(ACCESS_TOKEN, authoAccessToken.getOpenid());
    }

}
